#include <pthread.h>
#include <iostream>
#include <string>
#include <string.h>
#include <cstdlib>
#include <unistd.h>

using namespace std;

void *func1_routine(void *arg)
{
    cout << "线程开始执行" << endl;

    // pthread_cancel(pthread_self());
    sleep(10);
    cout << "线程取消成功" << endl;
    char *str = (char *)malloc(10);
    strcpy(str, "11");
    return (void *)str;
}

void func1()
{

    pthread_t tid;
    pthread_cancel(pthread_self());
    pthread_create(&tid, nullptr, func1_routine, nullptr);
    void *result;
    int ret = pthread_join(tid, &result); // join的第二个参数可以作为返回值来回收
    if (ret == 0)
        cout << "线程等待成功" << endl;
    cout << (char *)result << endl;
    free((char *)result);
}

int a = 100;
__thread int c = 100;
void *func2_routine(void *arg)
{
    static int b = 10;//这是在进程的静态区
    while (1)
    {
        sleep(1);
        cout << pthread_self()<<" a= "<<(++a) <<" b = "<< ++b<<" c = "<<++c<<endl;
    }
}

int main()
{
    pthread_t t1, t2, t3;
    pthread_create(&t1, nullptr, func2_routine, nullptr);
    pthread_create(&t2, nullptr, func2_routine, nullptr);
    pthread_create(&t3, nullptr, func2_routine, nullptr);
    pthread_detach(t1);
    pthread_detach(t2);
    pthread_detach(t3);
    sleep(10);
    cout<<"主线程退出"<<endl;
    return 0;
}